<template>
  <view>
    <!-- <view>接单页面跳转中...</view> -->
  </view>
</template>

<script>
  import func from '@/utils/funlogin.js';
  import {
    getAccessToken,
    setTenantId,
    removeWayBillNo,
    getTenantId,
    setToken,
    setDriverId,
    setOpenId
  } from '@/utils/auth';
  import {
    getOpenIdByCode,
    getTenantsByOpenId,
    getPhoneByOpenid,
    wxPhoneLogin
  } from '@/api/login.js';
  import { getDriving } from '@/api/me.js';
  export default {
    data() {
      return {
        isLogin: false,
        privacyShow: false,
        tenantId: null,
        tenantList: [],
        openid: '',
        dataSource: 0 //0:系统自建 1:集运2.0
      };
    },
    setOpenShare: function (data) {
      let that = this;
      if (that.$wechat.isWeixin()) {
        let configAppMessage = {
          desc: data.synopsis,
          title: data.title,
          link: location.href,
          imgUrl: data.img
        };
        that.$wechat.wechatEvevt(
          ['updateAppMessageShareData', 'updateTimelineShareData'],
          configAppMessage
        );
      }
    },
    onLoad(options) {
      removeWayBillNo();
      uni.removeStorageSync('scanData');
      uni.removeStorageSync('ysjhData');
      uni.removeStorageSync('isSetSjxx');
      if (options.deviceId) {
        uni.setStorageSync('scanData', { deviceId: options.deviceId });
      }
      if (options.p && options.t) {
        uni.setStorageSync('ysjhData', {
          planId: options.p,
          tenantId: options.t,
          onlineGoodsSwitch: options.o,
          isOperation: options.isOperation
        });
      }
      if (options.planId && options.tenantId) {
        uni.setStorageSync('ysjhData', {
          planId: options.planId,
          tenantId: options.tenantId,
          saleSwitch: options.saleSwitch,
          dataSources: options.dataSources,
          onlineGoodsSwitch: options.onlineGoodsSwitch,
          isOperation: options.isOperation
        });
      }
      if (options.q) {
        const url = decodeURIComponent(options.q);
        const query = this.handleQuery(url)
        const queryKeys = Object.keys(query)
        if (queryKeys.includes('deviceId')) {
          uni.setStorageSync('scanData', { deviceId: query.deviceId });
        }
        if (queryKeys.includes('planId') && queryKeys.includes('tenantId')) {
          uni.setStorageSync('ysjhData', {
            planId: query.planId,
            tenantId: query.tenantId,
            saleSwitch: query.saleSwitch,
            dataSources: query.dataSources,
            onlineGoodsSwitch: query.onlineGoodsSwitch,
            isOperation: query.isOperation
          });
        }
        if (queryKeys.includes('p') && queryKeys.includes('t')) {
          uni.setStorageSync('ysjhData', {
            planId: query.p,
            tenantId: query.t,
            onlineGoodsSwitch: query.o,
            isOperation: query.isOperation
          });
        }
      }
      this.getLoginStatus();
    },
    onShow() {
      wx.setScreenBrightness({
        value: 0.7
      });
    },
    onHide() { },
    methods: {
      goToLink() {
        wx.navigateToMiniProgram({
          appId: 'wxfb7d707ac051aad5', // 目标小程序的 AppID  
          path: 'pages/index?param1=value1', // 目标小程序内的页面路径，可带参数  
          extraData: {
            foo: 'bar' // 传递给目标小程序的参数  
          },
          envVersion: 'release', // 打开正式版的小程序  
          success(res) {
            // 跳转成功的回调  
            console.log('跳转成功', res);
          },
          fail(err) {
            // 跳转失败的回调  
            console.error('跳转失败', err);
          }
        });
      },
      handleQuery(query) {
        const obj = {}
        const paramsStr = query?.split('?')?.[2]?.split('#')?.[0]
        const queryList = paramsStr?.split('&') || []
        queryList.forEach(value => {
          const valueList = value.split('=')
          obj[valueList[0]] = valueList[1]
        })
        return obj
      },
      //用户无感知登录
      async loginWx() {
        //获取wx code
        const code = await func.wxLogin();
        const openId = await getOpenIdByCode(code);
        setOpenId(openId.data);
        const res = await getPhoneByOpenid(openId.data);
        if (res.code == 0 && res.data) {
          this.login(res.data);
        } else {
          this.setStorageForType()
          this.$tab.reLaunch(`/pages/login?type=code`);
        }
      },
      async login(phone) {
        const code = await func.wxLogin();
        const res = await wxPhoneLogin({ phoneCode: phone, loginCode: code })
        if (res.code === 0) {
          setToken({
            accessToken: res.data?.accessToken,
            refreshToken: res.data?.refreshToken
          });
          setDriverId(res.data?.userId);
          this.getUserInfor();
        } else {
          this.setStorageForType()
          this.$tab.reLaunch(`/pages/login?type=code`);
        }
      },
      // 获取登录状态
      async getLoginStatus() {
        if (uni.getStorageSync('scanData')) {
          const deviceId = uni.getStorageSync('scanData').deviceId;
          if (!!deviceId) {
            this.$tab.reLaunch(`/pages/scanCodeforDriver?deviceId=${deviceId}`);
          } else {
            toast('扫码出错');
          }
          return;
        }
        const tenantId = uni.getStorageSync('ysjhData').tenantId;
        if (getAccessToken() && getTenantId() && getTenantId() === tenantId) {
          this.getUserInfor();
        } else {
          if (tenantId) {
            setTenantId(tenantId);
          }
          this.loginWx();
        }
      },
      //获取司机用户信息
      async getUserInfor() {
        try {
          const res = await getDriving();
          this.$store.commit('SET_NAME', res.data?.driverName);
          this.$store.commit('SET_PHONE', res.data?.mobile);
          if (res.code === 0) {
            this.linkToNextPage(res.data)
          } else {
            toast(res.msg);
          }
        } catch (e) {
          return;
        }
      },
      linkToNextPage(result) {
        //存贮司机信息
        uni.setStorageSync('sjxxData', result);
        const transData = uni.getStorageSync('ysjhData');
        if (!result?.isIdIdentified) {
          this.setStorageForType()
          // 身份没有实名认证
          if (transData.onlineGoodsSwitch === '1' || transData.onlineGoodsSwitch === '0') {
            this.$tab.reLaunch('/packageB/pages/mine/driver-auth/driver-auth?type=code');
          } else if (transData.dataSources === '1') {
            this.$tab.reLaunch('/packageB/pages/mine/driver-auth/driver-auth?type=code');
          } else if (transData.saleSwitch === '0') {
            this.$tab.reLaunch('/packageB/pages/mine/driver-auth/driver-auth?type=code');
          } else {
            this.$tab.reLaunch('/packageB/pages/mine/driver-auth/driver-auth?type=code');
          }
          return
        }
        if (transData.onlineGoodsSwitch === '1' || transData.onlineGoodsSwitch === '0') {
          // 跳转到网货的接单页面
          this.$tab.reLaunch('/pages/receivingNet?codes=true');
        } else if (transData.dataSources === '1') {
          // 跳转到集运的接单页面
          this.$tab.reLaunch('/pages/receivingJY?codes=true');
        } else if (transData.saleSwitch === '0') {
          // 跳转到百吉的接单页面
          this.$tab.reLaunch('/pages/receivingBJ?codes=true');
        } else {
          // 跳转到计量的接单页面
          this.$tab.reLaunch('/pages/receiving?codes=true');
        }
      },
      setStorageForType() {
        const transData = uni.getStorageSync('ysjhData');
        if (transData.onlineGoodsSwitch === '1' || transData.onlineGoodsSwitch === '0') {
          uni.setStorageSync('isSetSjxx', 'net')
        } else if (transData.dataSources === '1') {
          uni.setStorageSync('isSetSjxx', 'jy')
        } else if (transData.saleSwitch === '0') {
          uni.setStorageSync('isSetSjxx', 'bj')
        } else {
          uni.setStorageSync('isSetSjxx', 'jl')
        }
      }
    }
  };
</script>

<style lang="scss"></style>